﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;

namespace mojoPortal.Web.RS.AppCode.Lib
{
    public class RSCommonFunctions : System.Web.UI.UserControl
    {
        public static void SetControlsEnabledState(Control pnl, bool bState = false)
        {
            foreach (Control ctrl in pnl.Controls)
            {
                if (ctrl is UpdatePanel)
                {
                    SetControlsEnabledState(ctrl, bState);
                }
                if (ctrl is Panel)
                {
                    SetControlsEnabledState(ctrl, bState);
                }
                if (ctrl is TextBox)
                {
                    ((TextBox)(ctrl)).Enabled = bState;
                }
                if (ctrl is DropDownList)
                {
                    ((DropDownList)(ctrl)).Enabled = bState;
                }
                if (ctrl is CheckBox)
                {
                    ((CheckBox)(ctrl)).Enabled = bState;
                }
                if (ctrl is CheckBoxList)
                {
                    ((CheckBoxList)(ctrl)).Enabled = bState;
                }
                if (ctrl is LinkButton)
                {
                    if (((LinkButton)(ctrl)).Text.Contains("View") || 
                        ((LinkButton)(ctrl)).Text.Contains("Add") || 
                        ((LinkButton)(ctrl)).Text.Contains("Map") ||
                        ((LinkButton)(ctrl)).Text.Contains("Roll") ||
                        ((LinkButton)(ctrl)).Text.Contains("Convert") || 
                        ((LinkButton)(ctrl)).Text.Contains("Manage Permission") || 
                        ((LinkButton)(ctrl)).Text.Contains("Generate Invoice"))
                    { ; }
                    else
                        ((LinkButton)(ctrl)).Enabled = bState;
                }
            }
        }
        
        public static string GetRSCompanyConnectionString()
        {
            string rsCompanyConnectionString = string.Empty;
            mojoPortal.Business.SiteUser siteUser = mojoPortal.Web.SiteUtils.GetCurrentSiteUser();
            if (siteUser != null && siteUser.MobilePin.Length > 0)
            {
                String strSQL = "select e.companyid, c.connectionstring from rs_tblEmployee e inner join rs_tblcompany c on e.companyid=c.companyid where e.PIN=@pin and e.EnableLogin=1 and e.IsActive=1";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReadyServiceConnectionStringMain"].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@pin";
                param.Value = siteUser.MobilePin;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    rsCompanyConnectionString = myDataReader["ConnectionString"].ToString();
                }
                myConnection.Close();
            }

            if (string.IsNullOrEmpty(rsCompanyConnectionString))
            {
                throw (new ArgumentNullException("ConnectionString is missing from ReadyServiceMain.dbo.rs_tblCompany for PIN: " + siteUser.MobilePin));
            }
            else
                return rsCompanyConnectionString;
        }

        public static bool ValidateReadyServiceUserPIN()
        {
            bool ret = false;
            mojoPortal.Business.SiteUser siteUser = mojoPortal.Web.SiteUtils.GetCurrentSiteUser();
            if (siteUser != null && siteUser.MobilePin.Length > 0)
            {
                String strSQL = "select e.companyid, e.pin from rs_tblEmployee e inner join rs_tblcompany c on e.companyid=c.companyid where e.PIN=@pin and e.EnableLogin=1 and e.IsActive=1";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReadyServiceConnectionStringMain"].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@pin";
                param.Value = siteUser.MobilePin;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                if (myDataReader.HasRows)
                {
                    ret = true;
                }
                myConnection.Close();
            }
            return ret;
        }

        public static bool ValidateReadyServiceUserPIN2(ref string rsModule, ref string rsLandingPageURL)
        {
            bool ret = false;
            mojoPortal.Business.SiteUser siteUser = mojoPortal.Web.SiteUtils.GetCurrentSiteUser();
            if (siteUser != null && siteUser.MobilePin.Length > 0)
            {
                String strSQL = "select e.companyid, c.module, c.landingpageurl, e.pin from rs_tblEmployee e inner join rs_tblcompany c on e.companyid=c.companyid where e.PIN=@pin and e.EnableLogin=1 and e.IsActive=1";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReadyServiceConnectionStringMain"].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@pin";
                param.Value = siteUser.MobilePin;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                if (myDataReader.HasRows)
                {
                    ret = true;
                    myDataReader.Read();
                    rsModule = myDataReader["module"].ToString();
                    rsLandingPageURL = myDataReader["landingpageurl"].ToString();
                }
                myConnection.Close();
            }
            return ret;
        }

        public static void ApplyAttributeRule(Control ctr, int companyid, string controlname)
        {
            string container = "";
            if (controlname.Length > 0)
                container = controlname;
            else
                container = HttpContext.Current.Request.Url.AbsolutePath;

            if (companyid > 0)
            {
                string strSQL = "SELECT CommandName,PanelId,LabelId,LabelDisplayText,Container,CompanyId FROM rs_tblPageAttributeRule WHERE CompanyId=@CompanyId AND IsActive=1 AND (CHARINDEX(Container, @Container) > 0)";

                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@Companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@Container";
                param.Value = container;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    string commandname = "";
                    Panel pnl = null;
                    Label lbl = null;
                    while (myDataReader.Read())
                    {
                        commandname = myDataReader["CommandName"].ToString();
                        if (commandname.ToUpper() == "HIDE")
                        {
                            pnl = (Panel)ctr.FindControl(myDataReader["PanelId"].ToString());
                            if (pnl != null)
                                pnl.Visible = false;
                        }
                        if (commandname.ToUpper() == "RENAME")
                        {
                            pnl = (Panel)ctr.FindControl(myDataReader["PanelId"].ToString());
                            if (pnl != null)
                            {
                                lbl = (Label)pnl.FindControl(myDataReader["LabelId"].ToString());
                                if (lbl != null)
                                    lbl.Text = myDataReader["LabelDisplayText"].ToString();
                            }
                        }
                    }
                }
            }
        }
        public static void ApplyGridViewColumnRule(Control ctr, int companyid, string controlname)
        {
            string container = "";
            if (controlname.Length > 0)
                container = controlname;
            else
                container = HttpContext.Current.Request.Url.AbsolutePath;

            if (companyid > 0)
            {
                string strSQL = "SELECT Container,CommandName,GridViewId,ColumnIndex,ColumnHeaderText,CompanyId FROM rs_tblPageGridViewColumnRule WHERE CompanyId=@CompanyId AND IsActive=1 AND (CHARINDEX(Container, @Container) > 0)";

                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@Companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@Container";
                param.Value = container;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    string commandname = "";
                    string columnheadertext = "";
                    int columnindex = 0;
                    GridView gv = null;

                    while (myDataReader.Read())
                    {
                        commandname = myDataReader["CommandName"].ToString();
                        if (commandname.ToUpper() == "HIDE")
                        {
                            gv = (GridView)ctr.FindControl(myDataReader["GridViewId"].ToString());
                            if (gv != null)
                            {
                                columnindex = int.Parse(myDataReader["ColumnIndex"].ToString());
                                if(columnindex >= 0)
                                    gv.Columns[columnindex].Visible = false;
                            }
                        }
                        if (commandname.ToUpper() == "RENAME")
                        {
                            gv = (GridView)ctr.FindControl(myDataReader["GridViewId"].ToString());
                            if (gv != null)
                            {
                                columnindex = int.Parse(myDataReader["ColumnIndex"].ToString());
                                if (columnindex >= 0)
                                {
                                    columnheadertext = myDataReader["ColumnHeaderText"].ToString();
                                    gv.Columns[columnindex].HeaderText = columnheadertext;
                                }
                            }
                        }
                    }
                }
            }
        }

        public static bool IsNumeric(string value)
        {
            for (int i = 0; i < value.Length; i++)
            {
                if (Char.IsNumber(value, i) == false)
                    return false;
            }
            return true;
        }

        public static ReadyServiceUser GetReadyServiceUser()
        {
            ReadyServiceUser rsUser = new ReadyServiceUser();
            if (rsUser != null && rsUser.LastName != null && rsUser.MobilePin != null)
            {
                String strSQL = "select e.*, g.groupname, g.rsrolename, c.CompanyName, c.CompanyEmail, c.CompanyPhone, c.PhotoPath, c.AttachmentPath from rs_tblEmployee e left join rs_tblGroup g on e.GroupId=g.GroupId inner join rs_tblCompany c on e.companyid=c.companyid where e.username=@username and e.pin=@pin and e.isactive=1 and e.enablelogin=1";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@username";
                param.Value = rsUser.LoginName;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.NVarChar;
                param.ParameterName = "@pin";
                param.Value = rsUser.MobilePin;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

                rsUser.RSEmployeeId = 0;
                rsUser.RSCompanyId = 0;
                rsUser.RSReportsTo = 0;
                rsUser.RSCompanyName = "";
                rsUser.RSCompanyEmail = "";
                rsUser.RSCompanyPhone = "";
                rsUser.RSRoleName = "";
                rsUser.RSGroupName = "";
                rsUser.RSIsUserAuthenticated = false;
                rsUser.RSSpecialPermission = "READ";
                rsUser.RSCanWrite = false;
                rsUser.RSCanRead = false;
                rsUser.RSCanDelete = false;
                rsUser.RSIsLicAgent = false;
                rsUser.RSPhotoPath = "";
                rsUser.RSAttachmentPath = "";
                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    rsUser.RSIsUserAuthenticated = true;
                    rsUser.RSFirstName = myDataReader["FirstName"].ToString();
                    rsUser.RSLastName = myDataReader["LastName"].ToString();
                    rsUser.RSCompanyName = myDataReader["CompanyName"].ToString();
                    rsUser.RSCompanyEmail = myDataReader["CompanyEmail"].ToString();
                    rsUser.RSCompanyPhone = myDataReader["CompanyPhone"].ToString();
                    rsUser.RSEmployeeId = int.Parse(myDataReader["EmployeeId"].ToString());
                    rsUser.RSReportsTo = int.Parse(myDataReader["ReportsTo"].ToString());
                    rsUser.RSCurrentUser = rsUser.FirstName + " " + rsUser.LastName;

                    rsUser.RSPhotoPath = myDataReader["PhotoPath"].ToString();
                    rsUser.RSAttachmentPath = myDataReader["AttachmentPath"].ToString();

                    if (myDataReader["CompanyId"] != DBNull.Value)
                        rsUser.RSCompanyId = int.Parse(myDataReader["CompanyId"].ToString());

                    if (myDataReader["CanRead"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanRead"].ToString()) == true)
                        {
                            rsUser.RSSpecialPermission = "READ";
                            rsUser.RSCanRead = true;
                        }
                    }
                    if (myDataReader["CanWrite"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanWrite"].ToString()) == true)
                        {
                            rsUser.RSSpecialPermission = "WRITE";
                            rsUser.RSCanWrite = true;
                        }
                    }
                    if (myDataReader["CanDelete"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["CanDelete"].ToString()) == true)
                        {
                            rsUser.RSSpecialPermission = "DELETE";
                            rsUser.RSCanDelete = true;
                        }
                    }
                    if (myDataReader["rsrolename"] != DBNull.Value)
                    {
                        rsUser.RSRoleName = myDataReader["rsrolename"].ToString().ToUpper();
                    }
                    if (myDataReader["groupname"] != DBNull.Value)
                    {
                        rsUser.RSGroupName = myDataReader["groupname"].ToString().ToUpper();
                    }
                    if (myDataReader["IsLicAgent"] != DBNull.Value)
                    {
                        if (Convert.ToBoolean(myDataReader["IsLicAgent"].ToString()) == true)
                        {
                            rsUser.RSIsLicAgent = true;
                        }
                    }

                }
                myConnection.Close();
            }
            return rsUser;
        }

        public static string GetMultiSelectValue(CheckBoxList chkList)
        {
            string combineListResult = string.Empty;
            for (int i = 0; i < chkList.Items.Count; i++)
            {
                if (chkList.Items[i].Selected)
                {
                    if (combineListResult == string.Empty)
                        combineListResult = chkList.Items[i].Text.Trim();
                    else
                        combineListResult = combineListResult + "; " + chkList.Items[i].Text.Trim();
                }
            }

            return combineListResult;
        }
        public static void ClearMultiSelectList(CheckBoxList chkList)
        {
            for (int i = 0; i < chkList.Items.Count; i++)
            {
                chkList.Items[i].Selected = false;
            }

        }
        public static void SetMultiSelectList(string AssignTo, CheckBoxList chkList)
        {
            string Names = AssignTo;
            string[] namesarr = Names.Split(';');
            bool found = false;
            foreach (var name in namesarr)
            {
                found = false;
                for (int i = 0; i < chkList.Items.Count; i++)
                {
                    if (chkList.Items[i].Text.ToLower() == name.Trim().ToString().ToLower())
                    {
                        chkList.Items[i].Selected = true;
                        found = true;
                        i = chkList.Items.Count + 1;
                    }
                }
                if (found == false && name.Length > 0)
                {
                    chkList.Items.Add(name.ToString());
                    chkList.Items.FindByValue(name.ToString()).Selected = true;
                }
            }
        }
        public static bool ValidatePermission(string RSGroupName, string RSPIN)
        {
            bool ret = false;
            string rsSysAdminPIN = ConfigurationManager.AppSettings["ReadyServiceSysAdminPIN"].ToString();
            if (RSGroupName == "ADMINISTRATOR" || 
                RSGroupName == "MANAGER" || 
                RSGroupName == "SUPERUSER" || 
                rsSysAdminPIN.Contains(RSPIN))
            {
                ret = true;
            }
            return ret;
        }
        public static string GetCompanyFullAddress(int companyid)
        {
            string fulladdress = string.Empty;
            String strSQL = "select CompanyId,CompanyName,Street,City,State,Country,Zip from rs_tblCompany where companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ReadyServiceConnectionStringMain"].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                fulladdress = myDataReader["Street"].ToString() + "<br />";
                fulladdress = fulladdress + myDataReader["City"].ToString() + ", ";
                fulladdress = fulladdress + myDataReader["State"].ToString() + " " + myDataReader["Zip"].ToString();
            }
            myConnection.Close();
            return fulladdress;
        }

        public static string GetEmployeeNameByID(int companyid, int employeeid)
        {
            string agentname = string.Empty;
            String strSQL = "select e.companyid, e.firstname, e.lastname from rs_tblEmployee e where e.employeeid=@employeeid and e.companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.NVarChar;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.NVarChar;
            param.ParameterName = "@employeeid";
            param.Value = employeeid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);

            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                agentname = myDataReader["FirstName"].ToString() + " " + myDataReader["LastName"].ToString();
            }
            myConnection.Close();
            return agentname;
        }
    }

}